// QCodeEditor
#include <QCXXCompleter>
#include <QLanguage>
#include <QSymbolExtracter>

// Qt
#include <QStringListModel>
#include <QFile>
#include <QTextBlock>
#include <QTextCursor>
#include <QAbstractItemView>

QCXXCompleter::QCXXCompleter(QObject *parent) :
    QCompleter(parent),
    m_extracter(nullptr)
{
    // 创建模型
    m_model = new QStringListModel(this);
    setModel(m_model);
    
    // 设置基本属性
    setCompletionColumn(0);
    setModelSorting(QCompleter::CaseInsensitivelySortedModel);
    setCaseSensitivity(Qt::CaseSensitive);
    setWrapAround(true);
    
    // 加载内置符号
    m_builtinSymbols.clear();
    
    Q_INIT_RESOURCE(qcodeeditor_resources);
    QFile fl(":/languages/cpp.xml");

    if (fl.open(QIODevice::ReadOnly))
    {
        QLanguage language(&fl);

        if (language.isLoaded())
        {
            auto keys = language.keys();
            for (auto&& key : keys)
            {
                auto names = language.names(key);
                m_builtinSymbols.append(names);
            }
        }
        
        fl.close();
    }
    
    // 初始化特殊补全项
    initSpecialCompletions();
    
    // 更新模型
    updateCompleterModel();
}

QCXXCompleter::~QCXXCompleter()
{
    // m_model和m_extracter由QObject系统自动释放
}

void QCXXCompleter::initSpecialCompletions()
{
    // 添加标准C++代码模板
    addSpecialCompletion("main", "int main(int argc, char *argv[])\n{\n    \n    return 0;\n}");
    addSpecialCompletion("class", "class ClassName\n{\npublic:\n    ClassName();\n    ~ClassName();\n\nprivate:\n    \n};");
    addSpecialCompletion("struct", "struct StructName\n{\n    \n};");
    addSpecialCompletion("for", "for (int i = 0; i < n; ++i) {\n    \n}");
    addSpecialCompletion("while", "while (condition) {\n    \n}");
    addSpecialCompletion("do", "do {\n    \n} while (condition);");
    addSpecialCompletion("if", "if (condition) {\n    \n}");
    addSpecialCompletion("else", "else {\n    \n}");
    addSpecialCompletion("switch", "switch (expression) {\ncase value1:\n    \n    break;\ndefault:\n    \n    break;\n}");
    addSpecialCompletion("try", "try {\n    \n} catch (std::exception& e) {\n    \n}");
    
    // 添加常用模板
    addSpecialCompletion("vector", "std::vector<>");
    addSpecialCompletion("map", "std::map<,>");
    addSpecialCompletion("shared_ptr", "std::shared_ptr<>");
    addSpecialCompletion("unique_ptr", "std::unique_ptr<>");
    addSpecialCompletion("function", "std::function<>");
    
    // 常用Qt模板
    addSpecialCompletion("QString", "QString()");
    addSpecialCompletion("QList", "QList<>");
    addSpecialCompletion("QMap", "QMap<,>");
    addSpecialCompletion("connect", "connect(sender, &SenderClass::signal, receiver, &ReceiverClass::slot);");
}

void QCXXCompleter::addSpecialCompletion(const QString& keyword, const QString& expansion)
{
    m_specialCompletions[keyword] = expansion;
    
    // 确保特殊关键字也出现在补全列表中
    QStringList list;
    
    // 获取当前模型中的所有项
    QStringListModel* model = qobject_cast<QStringListModel*>(this->model());
    if (model) {
        list = model->stringList();
    }
    
    // 如果列表中没有这个关键字，添加它
    if (!list.contains(keyword)) {
        list.append(keyword);
        list.sort(Qt::CaseInsensitive);
        
        if (model) {
            model->setStringList(list);
        }
    }
}

QString QCXXCompleter::getSpecialCompletion(const QString& keyword) const
{
    return m_specialCompletions.value(keyword, QString());
}

bool QCXXCompleter::isSpecialCompletion(const QString& text) const
{
    return m_specialCompletions.contains(text);
}

QString QCXXCompleter::pathFromIndex(const QModelIndex& index) const
{
    if (!index.isValid()) {
        return QString();
    }
    
    return index.data().toString();
}

QStringList QCXXCompleter::splitPath(const QString& path) const
{
    // 如果是双冒号语法（命名空间或类成员访问）
    if (path.contains("::")) {
        int lastScopePos = path.lastIndexOf("::");
        if (lastScopePos > 0) {
            // 获取作用域名称（类名或命名空间）
            QString scopeName = path.left(lastScopePos);
            // 获取当前正在输入的成员前缀
            QString memberPrefix = path.mid(lastScopePos + 2);
            
            // 清空当前补全列表
            m_currentCompletionList.clear();
            m_currentCompletionObject = scopeName;
            
            // 如果有符号提取器，获取对象成员
            if (m_extracter) {
                // 确保符号提取器已更新最新代码
                QStringList symbols = m_extracter->symbols();
                
                // 获取类/命名空间的成员
                m_currentCompletionList = m_extracter->getObjectMembers(scopeName);
                
                // 如果没有找到成员，尝试从类型信息中查找
                if (m_currentCompletionList.isEmpty()) {
                    QString objectType = m_extracter->getObjectType(scopeName);
                    
                    if (!objectType.isEmpty()) {
                        m_currentCompletionList = m_extracter->getObjectMembers(objectType);
                    }
                }
                
                // 移除用户当前输入的完全匹配项
                if (!memberPrefix.isEmpty()) {
                    m_currentCompletionList.removeAll(memberPrefix);
                }
            }
            
            // 设置临时模型
            QStringListModel* tempModel = qobject_cast<QStringListModel*>(model());
            if (tempModel) {
                // 根据前缀排序列表，让匹配度更高的排在前面
                if (!memberPrefix.isEmpty()) {
                    QStringList startsWithMatches, containsMatches, otherMatches;
                    for (const QString& item : m_currentCompletionList) {
                        if (item.startsWith(memberPrefix, Qt::CaseInsensitive)) {
                            startsWithMatches << item;
                        } else if (item.contains(memberPrefix, Qt::CaseInsensitive)) {
                            containsMatches << item;
                        } else {
                            otherMatches << item;
                        }
                    }
                    
                    // 按照优先级合并列表
                    startsWithMatches.sort(Qt::CaseInsensitive);
                    containsMatches.sort(Qt::CaseInsensitive);
                    otherMatches.sort(Qt::CaseInsensitive);
                    
                    QStringList sortedList = startsWithMatches + containsMatches + otherMatches;
                    m_currentCompletionList = sortedList;
                } else {
                    // 无前缀时简单排序
                    m_currentCompletionList.sort(Qt::CaseInsensitive);
                }
                
                // 直接设置模型的字符串列表
                tempModel->setStringList(m_currentCompletionList);
                
                // 强制显示补全弹出窗口
                if (popup()) {
                    popup()->setVisible(true);
                    popup()->update();
                }
            }
            
            return QStringList(memberPrefix);
        }
    } 
    // 点号语法（对象成员访问）
    else if (path.contains(".")) {
        int lastDotPos = path.lastIndexOf(".");
        if (lastDotPos > 0) {
            // 获取对象名
            QString objectName = path.left(lastDotPos);
            // 获取当前正在输入的成员前缀
            QString memberPrefix = path.mid(lastDotPos + 1);
            
            // 清空当前补全列表
            m_currentCompletionList.clear();
            m_currentCompletionObject = objectName;
            
            // 如果有符号提取器，获取对象成员
            if (m_extracter) {
                // 确保符号提取器已更新最新代码
                QStringList symbols = m_extracter->symbols();
                
                // 获取对象的成员
                m_currentCompletionList = m_extracter->getObjectMembers(objectName);
                
                // 如果没有找到成员，尝试从类型信息中查找
                if (m_currentCompletionList.isEmpty()) {
                    QString objectType = m_extracter->getObjectType(objectName);
                    
                    if (!objectType.isEmpty()) {
                        m_currentCompletionList = m_extracter->getObjectMembers(objectType);
                    }
                }
                
                // 移除用户当前输入的完全匹配项
                if (!memberPrefix.isEmpty()) {
                    m_currentCompletionList.removeAll(memberPrefix);
                }
            }
            
            // 设置临时模型
            QStringListModel* tempModel = qobject_cast<QStringListModel*>(model());
            if (tempModel) {
                // 根据前缀排序列表，让匹配度更高的排在前面
                if (!memberPrefix.isEmpty()) {
                    QStringList startsWithMatches, containsMatches, otherMatches;
                    for (const QString& item : m_currentCompletionList) {
                        if (item.startsWith(memberPrefix, Qt::CaseInsensitive)) {
                            startsWithMatches << item;
                        } else if (item.contains(memberPrefix, Qt::CaseInsensitive)) {
                            containsMatches << item;
                        } else {
                            otherMatches << item;
                        }
                    }
                    
                    // 按照优先级合并列表
                    startsWithMatches.sort(Qt::CaseInsensitive);
                    containsMatches.sort(Qt::CaseInsensitive);
                    otherMatches.sort(Qt::CaseInsensitive);
                    
                    QStringList sortedList = startsWithMatches + containsMatches + otherMatches;
                    m_currentCompletionList = sortedList;
                } else {
                    // 无前缀时简单排序
                    m_currentCompletionList.sort(Qt::CaseInsensitive);
                }
                
                // 直接设置模型的字符串列表
                tempModel->setStringList(m_currentCompletionList);
                
                // 强制显示补全弹出窗口
                if (popup()) {
                    popup()->setVisible(true);
                    popup()->update();
                }
            }
            
            return QStringList(memberPrefix);
        }
    }
    
    // 记录用户当前输入
    QString currentInput = path.trimmed();
    
    // 临时创建一个不包含当前输入的列表
    if (!currentInput.isEmpty()) {
        QStringListModel* tempModel = qobject_cast<QStringListModel*>(model());
        if (tempModel) {
            QStringList completeList = tempModel->stringList();
            
            // 移除用户当前输入的完全匹配项
            completeList.removeAll(currentInput);
            
            // 设置新的列表
            tempModel->setStringList(completeList);
        }
    }
    
    return QCompleter::splitPath(path);
}

void QCXXCompleter::setExtracter(QSymbolExtracter* extracter)
{
    // 断开旧的连接
    if (m_extracter) {
        disconnect(m_extracter, &QSymbolExtracter::symbolsUpdated,
                  this, &QCXXCompleter::onSymbolsUpdated);
    }
    
    m_extracter = extracter;
    
    // 建立新的连接
    if (m_extracter) {
        connect(m_extracter, &QSymbolExtracter::symbolsUpdated,
                this, &QCXXCompleter::onSymbolsUpdated);
        
        // 立即更新符号列表
        onSymbolsUpdated(m_extracter->symbols());
    }
}

QSymbolExtracter* QCXXCompleter::extracter() const
{
    return m_extracter;
}

void QCXXCompleter::updateUserSymbols(const QStringList& userSymbols)
{
    m_userSymbols = userSymbols;
    updateCompleterModel();
}

void QCXXCompleter::onSymbolsUpdated(const QStringList& symbols)
{
    m_userSymbols = symbols;
    updateCompleterModel();
}

void QCXXCompleter::updateCompleterModel()
{
    // 合并内置符号和用户符号
    QStringList completeList = m_builtinSymbols + m_userSymbols;
    
    // 添加特殊补全项的关键字
    QStringList specialKeys = m_specialCompletions.keys();
    for (const QString& key : specialKeys) {
        if (!completeList.contains(key)) {
            completeList.append(key);
        }
    }
    
    // 移除重复项
    completeList.removeDuplicates();
    
    // 排序
    completeList.sort(Qt::CaseInsensitive);
    
    // 获取当前补全前缀
    QString currentCompletion = completionPrefix().trimmed();
    
    // 如果有当前输入内容，从列表中移除完全匹配项
    if (!currentCompletion.isEmpty()) {
        completeList.removeAll(currentCompletion);
    }
    
    // 更新模型
    m_model->setStringList(completeList);
} 